package seu.xml.analysis;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 * 存储UML图元素集合
 * @author cy
 * 
 */
public class Diagram {
	private ArrayList<Element> a;
	public Diagram(){
		a = new ArrayList<Element>();
	}
	/**
	 * 读取xml文档	
	 * @param path 文件绝对路径
	 */
	public void readXML(String path){
		try {
			File f = new File(path);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
			DocumentBuilder builder = factory.newDocumentBuilder(); 
			Document doc = builder.parse(f); 
			NodeList nl = doc.getElementsByTagName("element"); 
			for (int i = 0; i < nl.getLength(); i++){
				Element ee = new Element();
				Node nd;
				nd = doc.getElementsByTagName("type").item(i).getFirstChild();
				if(nd != null) ee.setType(nd.getNodeValue());
				nd = doc.getElementsByTagName("x").item(i).getFirstChild();
				if(nd != null) ee.setX(Integer.parseInt(nd.getNodeValue()));
				nd = doc.getElementsByTagName("y").item(i).getFirstChild();
				if(nd != null) ee.setY(Integer.parseInt(nd.getNodeValue()));
				nd = doc.getElementsByTagName("w").item(i).getFirstChild();
				if(nd != null) ee.setW(Integer.parseInt(nd.getNodeValue()));
				nd = doc.getElementsByTagName("h").item(i).getFirstChild();
				if(nd != null) ee.setH(Integer.parseInt(nd.getNodeValue()));
				nd = doc.getElementsByTagName("panel_attributes").item(i).getFirstChild();
				if(nd != null) ee.setPanel_attributes(nd.getNodeValue());
				nd = doc.getElementsByTagName("additional_attributes").item(i).getFirstChild();
				if(nd != null) ee.setAdditional_attributes(nd.getNodeValue());
				a.add(ee);
			}
		}catch(ParserConfigurationException e){
			e.printStackTrace(); 
		}catch(SAXException e){
			e.printStackTrace(); 
		}catch(IOException e){
			e.printStackTrace(); 
		}
	}
	public ArrayList<Element> getDiagram(){
		return a;
	}
	public void printDiagram(){
		for(Element e : a){
			System.out.println(e.getX()+"--"+e.getY()+"--"+e.getW()+"--"+e.getH());
		}
	}
	public static void main(String[] args){
		Diagram dg = new Diagram();
		//dg.readXML("simulate.uxf");
		dg.readXML("new.uxf");
		dg.printDiagram();
	}
}
